//------------------------------------------------------
// ContactCollection.java
//------------------------------------------------------

import javax.swing.JOptionPane;
import java.io.*;
import java.util.*;

public class ContactCollection {
	private Contact[] collection;
	private Contact[] search;
	private int count;
	private int count2;
	private int pass = 0;
	private String password = "000000";
	private String first_name;
	private String last_name;

	public ContactCollection() {
		collection = new Contact[100];
		search = new Contact[100];
		count = 0;
	}

	public void savedata() {// 저장버튼 눌렀을 때 모든 contacts 저장
		try {
			String file = "src/SaveFile.txt";
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter outFile = new PrintWriter(bw);
			String data = saveCollection();
			outFile.print(data);
			outFile.close();
			JOptionPane.showMessageDialog(null, "저장이 완료되었습니다.");
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "파일이 존재하지 않습니다.");
		}
	}
	
	public void savedata2() {// 저장버튼 눌렀을 때 모든 contacts 저장 테스트를 위해 만듦^^ㅋ
		try {
			String file = "src/SaveFile.txt";
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter outFile = new PrintWriter(bw);
			String data = saveCollection();
			outFile.print(data);
			outFile.close();
		} catch (IOException e) {
		}
	}

	public void loadCollection() {// 저장된 contacts 불러오는 메소드
		String line;
		Scanner fileScan, lineScan;
		try {
			fileScan = new Scanner(new File("src/SaveFile.txt"));
			while (fileScan.hasNext()) {
				line = fileScan.nextLine();
				lineScan = new Scanner(line);
				lineScan.useDelimiter("/");
				addContact(lineScan.next(), lineScan.next(), lineScan.next(), lineScan.next(), lineScan.next(), 
				lineScan.next(), lineScan.next(), lineScan.next(), lineScan.next(), lineScan.next(), lineScan.next());
			}
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "파일을 불러올 수가 없습니다.");
		}
		Store("", "");
	}

	public void savePW() {//파일에 패스워드 저장하는 메소드
		try {
			String file = "src/PWFile.txt";
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			PrintWriter outFile = new PrintWriter(bw);
			String data = GetPW();
			outFile.print(data);
			outFile.close();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "파일이 존재하지 않습니다.");
		}
	}

	public void loadPW() {// 지정된 파일에서 비밀번호 불러오기
		
		Scanner fileScan;
		try {
			fileScan = new Scanner(new File("src/PWFile.txt"));
			SetPW(fileScan.next());
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "파일을 불러올 수가 없습니다.");
		}
	}

	public String GetPW() {
		return password;
	}

	public Boolean IdentifyPW(String paw) {// 비밀번호 일치확인
		if (paw.equals(password))
			return true;
		else 
			return false;
	}

	public void SetPW(String npw) {
		password = npw;
	}

	public void SetPW2(String npw) {//비밀번호 바꾸는 메소드
		if (npw.length() < 6 || npw.equals("000000")){
			JOptionPane.showMessageDialog(null, "000000이 아닌 6자리 이상의 모든 문자로 설정 가능 합니다.");
			loadPW();	
		}
		else {
			password = npw;
			JOptionPane.showMessageDialog(null, "비밀번호가 갱신되었습니다.");
		}
	}
	
	public void SetPW3(String npw) {//비밀번호 바꾸는 메소드 테스트를 위해 만듦...ㅋ
		if (npw.length() < 6 || npw.equals("000000")){
			loadPW();	
		}
		else {
			password = npw;
		}
	}

	public String Getname() {
		String name;
		name = last_name + first_name;
		return name;
	}

	public void Store(String f_name, String l_name) { //first_name, last_name 매번 두개 호출하는게 번거로워서 메소드 만듦												
		first_name = f_name;
		last_name = l_name;
	}

	public void Store(int i) { // 리스트를 위해서 중복정의
		first_name = collection[i].getFirst_name();
		last_name = collection[i].getLast_name();
	}

	public void SearchStore(int i) {//이름 검색
		first_name = search[i].getFirst_name();
		last_name = search[i].getLast_name();
	}

	//contact 추가
	public void addContact(String fname, String lname, String pos, String dept, String comp, String addr, String tel, String fax, String mobile, String email, String homepg) {
		collection[count] = new Contact(fname, lname, pos, dept, comp, addr, tel, fax, mobile, email, homepg); 																											
		count++;
		Store(fname, lname); // view갱신
		sort();
	}

	public int findContact(String fname, String lname) {
		int index = count;
		for (int i = 0; i < count; i++){
			if (fname.equals(collection[i].getFirst_name()) && lname.equals(collection[i].getLast_name()))
				index = i;
		}
		return index;
	}

	public void search(String text) {
		String str = "";
		int j = 0;
		count2 = 0;
		for (int i = 0; i < count; i++) {
			str = collection[i].getLast_name() + collection[i].getFirst_name();
			if (str.contains(text)) {
				search[j++] = new Contact(collection[i].getFirst_name(), collection[i].getLast_name(), collection[i].getPosition(),
						collection[i].getDepartment(), collection[i].getCompany_name(), collection[i].getAddress(),
						collection[i].getTelephone_number(), collection[i].getFax_number(), collection[i].getMobile_number(),
						collection[i].getEmail_address(), collection[i].getHomepage());
				count2++;
			}
		}
	}

	public void modifyContact(String fname, String lname, String pos, String dept, String comp, String addr, String tel, String fax, String mobile, String email, String homepg){
		int i = findContact(first_name, last_name); // 현재 view에 있는 애를 찾음
		if (i != count) {
			collection[i].setFirst_name(fname);
			collection[i].setLast_name(lname);
			collection[i].setPosition(pos);
			collection[i].setDepartment(dept);
			collection[i].setCompany_name(comp);
			collection[i].setAddress(addr);
			collection[i].setTelephone_number(tel);
			collection[i].setFax_number(fax);
			collection[i].setMobile_number(mobile);
			collection[i].setEmail_address(email);
			collection[i].setHomepage(homepg); 
			Store(fname, lname); // view에 있는애 갱신
		}
	}

	public void deleteContact() {
		int i = findContact(first_name, last_name);
		if (i != count) {
			if (count == 1) {
				collection[0] = null;
				count--;
			} 
			else {
				while (i < count - 1) {
					collection[i] = collection[i + 1];
					i++;
				}
				collection[count - 1] = null;
				count--;
			}
			Store("", "");
		} 
		else 
			JOptionPane.showMessageDialog(null, "삭제 할 연락처 정보를 view에 띄워주세요.");
	}

	// ------------------------------------------------
	// 저장된 Contact의 개수 리턴
	// ------------------------------------------------
	public int getCount() {
		return count;
	}

	public int getCount2() {
		return count2;
	}
	
	public int getPass() {
		return pass;
	}

	public void setPass(int a) {
		pass = a;
	}
	
	//--------------------------------------

	public String searchFname() 
	{
		String firstname = first_name;
		return firstname;
	}
	
	public String searchLname()             
	{
		String lastname = last_name;
		return lastname;
	}

	public String searchPos() {
		int i = findContact(first_name, last_name);
		String pos = collection[i].getPosition();
		return pos;
	}

	public String searchDept() {
		int i = findContact(first_name, last_name);
		String dept = collection[i].getDepartment();
		return dept;
	}

	public String searchComp() {
		int i = findContact(first_name, last_name);
		String comp = collection[i].getCompany_name();
		return comp;
	}

	public String searchAddr() {
		int i = findContact(first_name, last_name);
		String addr = collection[i].getAddress();
		return addr;
	}

	public String searchTel() {
		int i = findContact(first_name, last_name);
		String tel = collection[i].getTelephone_number();
		return tel;
	}

	public String searchFax() {
		int i = findContact(first_name, last_name);
		String fax = collection[i].getFax_number();
		return fax;
	}

	public String searchMobile() {
		int i = findContact(first_name, last_name);
		String mobile = collection[i].getMobile_number();
		return mobile;
	}

	public String searchEmail() {
		int i = findContact(first_name, last_name);
		String email = collection[i].getEmail_address();
		return email;
	}

	public String searchHomepg() {
		int i = findContact(first_name, last_name);
		String homepg = collection[i].getHomepage();
		return homepg;
	}

	public String toString() // 방금 등록되거나 수정된 연락처의 정보 출력
	{
		String report = "";
		int i = findContact(first_name, last_name);
		report += collection[i].toString() + "\n";
		return report;
	}
	
	public String allContacts()//test위해 만듦 모든 contact report로 출력
	{
		String report = "";
		for(int i=0; i<count;i++)
		report += collection[i].toString() + "\n";
		return report;
	}

	public String list(int index) {//display에 리스트당 collection 배열원소 하나의 정보를 보여주기 위해서
		String report = "";
		report += collection[index].list();
		return report;
	}

	public String Searchlist(int index) {//검색리스트에 리스트당 search 배열원소 하나의 정보를 보여주기위해 만든 함수
		String report = "";
		report += search[index].list();
		return report;
	}

	/*public String searchlist() {
		String report = "";
		for (int i = 0; i < count2; i++)
			report += search[i].getLast_name() + search[i].getFirst_name() + "\n";
		return report;
	}*/

	public void sort() {//연락처들을 이름 순에 따라 정렬
		for (int i = 0; i < count; i++) {
			if ((collection[i].getLast_name().compareTo(last_name)) > 0) {
				Contact[] temp = new Contact[1];
				temp[0] = collection[i];
				collection[i] = collection[count - 1];
				collection[count - 1] = temp[0];
			}
			else if ((collection[i].getLast_name().compareTo(last_name) == 0) && (collection[i].getFirst_name().compareTo(first_name) > 0)) {
				Contact temp[] = new Contact[1];
				temp[0] = collection[i];
				collection[i] = collection[count - 1];
				collection[count - 1] = temp[0];
			}
		}
	}

	public String saveCollection() {//총 연략처 정보를 파일에 저장할 형태로 바꿔주는 함수
		String report = "";
		for (int i = 0; i < count; i++)
			report += collection[i].saveContact() + "\n";
		return report;
	}
}
